package com.ronsai.umtrack.base;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseRecyclerAdapter.BaseViewHolder> {

    private Context context;
    private int layoutId;
    private List<T> list;
    private List<View> headerViews = new ArrayList<>();
    private List<View> footerViews = new ArrayList<>();

    public BaseRecyclerAdapter(Context context, int layoutId, List<T> list) {
        this.context = context;
        this.layoutId = layoutId;
        this.list = list;
    }

    @Override
    public int getItemCount() {
        int listSize = list == null ? 0 : list.size();
        return headerViews.size() + footerViews.size() + listSize;
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        return new BaseViewHolder(LayoutInflater.from(context).inflate(layoutId, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        convert(holder, list.get(position), position);
    }

    public abstract void convert(BaseViewHolder holder, T item, int position);

    public void addHeaderView(View headerView) {
        headerViews.add(headerView);
        notifyDataSetChanged();
    }

    public void removeHeaderView(View headerView) {
        headerViews.remove(headerView);
        notifyDataSetChanged();
    }

    public void addFooterView(View FooterView) {
        headerViews.add(FooterView);
        notifyDataSetChanged();
    }

    public void removeFooterView(View FooterView) {
        headerViews.remove(FooterView);
        notifyDataSetChanged();
    }

    public static class BaseViewHolder extends RecyclerView.ViewHolder {

        private SparseArray<View> mViewMap;

        public BaseViewHolder(@NonNull View itemView) {
            super(itemView);
            mViewMap = new SparseArray<>();
        }

        public <T extends View> T getView(int id) {
            View view = mViewMap.get(id);
            if (view == null) {
                view = itemView.findViewById(id);
                mViewMap.put(id, view);
            }
            return (T) view;
        }

        public BaseViewHolder setText(int id, String text) {
            TextView textView = getView(id);
            if (textView != null) {
                textView.setText(text);
            }
            return this;
        }
    }

}
